#!/usr/bin/python3
# /usr/bin/env python
# -*- coding: UTF-8 -*-

from aip import AipOcr
from zhtools.langconv import *
from logs.Logger import Logger
import configparser
import common.const as const

'''
系统常量
'''
const.OCR = 'ocr'
const.APP_ID = 'app_id'
const.API_KEY = 'api_key'
const.SECRET_KEY = 'secret_key'
const.OCR_FILE = 'ocr_path'

'''
读取配置信息
'''
cf = configparser.ConfigParser()
cf.read("../config/config.ini", encoding='UTF-8')

secs = cf.sections()
options = cf.options(const.OCR)

""" 获取APPID AK SK """
APP_ID = cf.get(const.OCR, const.APP_ID)
API_KEY = cf.get(const.OCR, const.API_KEY)
SECRET_KEY = cf.get(const.OCR, const.SECRET_KEY)
""" 读取图片 """
file_path = cf.get(const.OCR, const.OCR_FILE)
# 调用AIP OCR方法
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


def get_file_content(file_path):
    with open(file_path, 'rb') as fp:
        return fp.read()


def traditional_2_simplified(sentence):
    """
    将sentence中的繁体字转为简体字
    :param sentence: 待转换的句子
    :return: 将句子中繁体字转换为简体字之后的句子
    """
    sentence = Converter('zh-hans').convert(sentence)
    return sentence


log = Logger("D:/logs/ocr.log", level='info')

image = get_file_content(file_path)
""" 调用通用文字识别（高精度版） """
client.basicGeneral(image);

""" 如果有可选参数 """
options = {}
options["detect_direction"] = "true"
options["probability"] = "true"

""" 带参数调用通用文字识别（高精度版） """
result = client.basicAccurate(image, options)
lines = result.get("words_result")
res_str = ''
for line in lines:
    res_str = res_str + line.get('words')
    log.logger.debug("Original OCR text： " + res_str)
    res_str = traditional_2_simplified(res_str)
    log.logger.debug("After Complex to Simple： " + res_str)
print(res_str)
